<?php

class Core_Model_Table_Setting extends Model_Table
{
	/**
	 * @var string
	 */
	protected $_name = 'core_settings';

	/**
	 * @param string $name
	 * @param string $value
	 * @param int $siteId
	 * @return void
	 */
	protected function _set($name, $value, $siteId)
	{
		/**
		 * correct format.
		 */
		$name = str_replace('_', '.', strtolower(trim($name)));

		if (strpos($name, '.') == false)
		{
			return;
		}

		$select = $this -> select() -> where('sid=?', $siteId) -> where('name=?', $name);

		$row = $this -> fetchRow($select);

		if (!is_object($row))
		{
			$row = $this -> fetchNew();
			$row -> name = $name;
			$row -> sid = $siteId;
			$row -> scope = substr($name, 0, strrpos($name, '.'));
		}
		$row -> value = $value;
		$row -> save();
	}

	/**
	 * @param string/array $name
	 * @param string $value
	 * @param int $siteId
	 * @return Core_Model_Table_Setting
	 */
	public function set($name, $value = null, $siteId = null)
	{
		if (null == $siteId)
		{
			$siteId = Nuo::getSiteId();
		}

		if (null === $value && is_array($name) && !is_string($name))
		{
			foreach ($name as $k => $v)
			{
				$this -> _set($k, $v, $siteId);
			}
			return;
		}

		$this -> _set($name, $value, $siteId);

		return $this;
	}

	/**
	 * @param string $name
	 * @param string $default
	 * @param int $siteId
	 * @return string
	 */
	public function get($name, $default = null, $siteId = null)
	{
		if (null == $siteId)
		{
			$siteId = Nuo::getSiteId();
		}
		/**
		 * correct format.
		 */
		$name = str_replace('_', '.', strtolower(trim($name)));

		if (strpos($name, '.') == false)
		{
			return $default;
		}

		$select = $this -> select() -> where('sid=?', $siteId) -> where('name=?', $name);

		$row = $this -> fetchRow($select);

		if (is_object($row))
		{
			return $row -> value;
		}

		return $default;
	}

	/**
	 * get all setting in a scope, delete scope from name to take it stured.
	 * @param string $scope
	 * @param int $siteId
	 * @return array
	 */
	public function getAll($scope, $siteId = null)
	{
		if (null == $siteId)
		{
			$siteId = Nuo::getSiteId();
		}

		$select = $this -> select() -> from($this -> _name, array(
				'name',
				'value'
		)) -> where('sid=?', $siteId) -> where('scope=?', $scope);

		$ret = array();
		
		$start =  strlen($scope) + 1;

		foreach ($this->fetchAll($select) as $row)
		{
			$ret[substr($row->name, $start)] = $row->value;
		}
		
		return $ret;
	}

}
